package com.xuecheng.media.service.impl;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.content.model.qo.QueryCourseBaseModel;
import com.xuecheng.api.media.model.MediaDTO;
import com.xuecheng.api.media.model.qo.QueryMediaModel;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.domain.page.PageRequestParams;
import com.xuecheng.common.domain.page.PageVO;
import com.xuecheng.common.enums.common.AuditEnum;
import com.xuecheng.common.enums.common.CommonEnum;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.content.common.constant.ContentErrorCode;
import com.xuecheng.media.common.constant.MediaErrorCode;
import com.xuecheng.media.common.utils.AliyunVODUtil;
import com.xuecheng.media.convert.MediaConvert;
import com.xuecheng.media.entity.Media;
import com.xuecheng.media.mapper.MediaMapper;
import com.xuecheng.media.service.MediaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;


@Slf4j
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    private MediaService mediaService;


    @Value("${aliyun.region}")
    private String regionId;

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    /*保存媒资功能
     * 业务分析：
     *   1.判断关键
     *       companyid  filename  fileid(videoId)
     *   2.给信息数据赋值默认值
     *       auditStatus：未审核
     *
     *   3.保存信息
     *   4.将数据库最新数据返回
     *
     * */
    @Transactional
    public MediaDTO createMedia(MediaDTO dto) {
        //1.判断关键数据是否为空
        //机构id
        if (ObjectUtils.isEmpty(dto.getCompanyId())) {
            ExceptionCast.cast(ContentErrorCode.E_120018);
        }
        //文件名字
        if (ObjectUtils.isEmpty(dto.getFilename())) {
            ExceptionCast.cast(MediaErrorCode.E_140006);
        }
        //文件标识
        if (ObjectUtils.isEmpty(dto.getFileId())) {
            ExceptionCast.cast(MediaErrorCode.E_140007);
        }

        //2.给信息数据赋值默认值
        //auditStatus：未审核

        //将dto转为po
        Media media = MediaConvert.INSTANCE.dto2entity(dto);
        //审核状态
        media.setAuditStatus(AuditEnum.AUDIT_UNPAST_STATUS.getCode());
        //保存数据
        mediaService.save(media);

        //3.判断是否保存超成功
        boolean result = mediaService.updateById(media);
        if (!result) {
            ExceptionCast.cast(MediaErrorCode.E_140001);
        }

        //4.将数据库里的最新信息返回
        LambdaUpdateWrapper<Media> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Media::getFileId,dto.getFileId());
        wrapper.set(Media::getCompanyId,dto.getCompanyId());
        wrapper.set(Media::getFilename,dto.getFilename());

        //将po转为dto
        MediaDTO mediaDTO = MediaConvert.INSTANCE.entity2dto(media);

        //返回dto
        return mediaDTO;
    }



    /**
     * 分页查询
     *
     * @param params    {@link PageRequestParams} 分页封装数据
     * @param model     {@link QueryMediaModel} 分页查询封装数据
     * @param companyId {@link Long} 教学机构的id标识
     * @return
     */
    public PageVO queryCourseList(PageRequestParams params, QueryMediaModel model, Long companyId) {

        // 1.判断关键数据
        // 分页数据 判断int合理性 ：要求数据不能为负数
        if (params.getPageSize() < 1) {
            params.setPageSize(PageRequestParams.DEFAULT_PAGE_SIZE);
        }
        if (params.getPageNo() < 1) {
            params.setPageNo(PageRequestParams.DEFAULT_PAGE_NUM);
        }


        if (ObjectUtils.isEmpty(companyId)) {
           ExceptionCast.cast(ContentErrorCode.E_120018);
        }


        // 2.构建分页对象数据
        Page<Media> page = new Page<>(params.getPageNo(), params.getPageSize());

        // 3.构建查询条件对象
        LambdaQueryWrapper<Media> wrapper = new LambdaQueryWrapper<>();

        //todo:课程名称条件
        wrapper.like(StringUtil.isNotBlank(model.getFilename()), Media::getFilename, model.getFilename());
        wrapper.eq(StringUtil.isNotBlank(model.getType()), Media::getType, model.getType());
        wrapper.eq(Media::getStatus, CommonEnum.USING_FLAG.getCode());
        if (!ObjectUtils.isEmpty(companyId)) {
            wrapper.eq(Media::getCompanyId, companyId);
        }

        //4.查询数据
        Page<Media> pageResult = mediaService.page(page, wrapper);

        List<Media> records = pageResult.getRecords();

        long total = pageResult.getTotal();

        //将当前数据po转为dto数据
        List dtos = Collections.EMPTY_LIST;

        if (!CollectionUtils.isEmpty(records)) {
            dtos = MediaConvert.INSTANCE.entitys2dtos(records);
        }

        //5,构建pagevo并返回
        return new PageVO(dtos, total, params.getPageNo(), params.getPageSize());
    }


    /**
     * 预览媒资
     * @param mediaId
     * @param companyId
     * @return
     */
    public String getVODUrl(Long mediaId,Long companyId) {

        // 1.判断业务数据
        if (ObjectUtils.isEmpty(mediaId)) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }
        // 2.根据媒资id获得媒资信息
        Media media = getById(mediaId);
        if (ObjectUtils.isEmpty(media)) {
            ExceptionCast.cast(CommonErrorCode.E_100104);
        }

        // 3.如果公司id不为空，对其进行判断
        if (!(ObjectUtils.isEmpty(companyId))) {
            if (!(ObjectUtils.nullSafeEquals(media.getCompanyId(), companyId))) {
                ExceptionCast.cast(CommonErrorCode.E_100108);
            }
        }

        String playUrl = getPlayUrl(media.getFileId());


        // 4.返回媒资的资源地址
        return playUrl;
    }


    private String getPlayUrl(String videoId) {

        String playUrl = "";
        try {

            DefaultAcsClient client =
                    AliyunVODUtil.initVodClient(regionId,accessKeyId,accessKeySecret);

            GetPlayInfoResponse response = AliyunVODUtil.getPlayInfo(client,videoId);

            List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();

            if (!(ObjectUtils.isEmpty(playInfoList))) {
                GetPlayInfoResponse.PlayInfo playInfo = playInfoList.get(0);
                playUrl = playInfo.getPlayURL();
            }

        } catch (Exception e) {
            ExceptionCast.cast(MediaErrorCode.E_140014);
        }
        return playUrl;
    }
}
